<?php

namespace Addons\ThinkSDK\Controller;
use Home\Controller\AddonsController;

class ThinkSDKController extends AddonsController{

	public function _initialize(){
		$this->addon_path = ONETHINK_ADDON_PATH.'ThinkSDK/';
		$config = get_addon_config('ThinkSDK');

		C("THINK_SDK_QQ", array(
			'APP_KEY'=>$config['qq_ak'],
			'APP_SECRET'=>$config['qq_sk'],
			'CALLBACK'=>$config['url_callback'].'qq',
		));

		C("THINK_SDK_SINA", array(
			'APP_KEY'=>$config['sina_ak'],
			'APP_SECRET'=>$config['sina_sk'],
			'CALLBACK'=>$config['url_callback'].'sina',
		));
	}

	public function login(){
		$type = I('get.type');
		$type = ucfirst($type);
		require_once $this->addon_path .'/lib/ThinkOauth.class.php';
		$sns  = \ThinkOauth::getInstance($type);

		//跳转到授权页面
		redirect($sns->getRequestCodeURL());
	}

	//授权回调地址
	public function callback(){
		$type = I('type');
		$code = I('code');
		(empty($type) || empty($code)) && $this->error('参数错误');

		//加载ThinkOauth类并实例化一个对象
		require_once $this->addon_path .'/lib/ThinkOauth.class.php';
		$sns = \ThinkOauth::getInstance($type);

		//腾讯微博需传递的额外参数
		$extend = null;
		if($type == 'tencent'){
			$extend = array('openid' => $this->_get('openid'), 'openkey' => $this->_get('openkey'));
		}

		//请妥善保管这里获取到的Token信息，方便以后API调用
		//调用方法，实例化SDK对象的时候直接作为构造函数的第二个参数传入
		//如： $qq = ThinkOauth::getInstance('qq', $token);
		$token = $sns->getAccessToken($code , $extend);

		//获取当前登录用户信息
		if(is_array($token)){
			$api = $type == 'qq'? 'user/get_user_info' : 'users/show';
			$param = $in = array(
				'action'=>'call',
				'token'=>$token,
				'api'=>$api,
				'type'=>$type,
			);
			$user = M('User')->find();
			$oauth = D('Addons://ThinkSDK/Oauth');
			if(!$id = $oauth->where("type='{$type}'")->find()){
				$oauth->add(array(
					'uid'=>$user['id'],
					'type'=>$type,
					'access_token'=>$token['access_token'],
					'create_time'=>date("Y-m-d H:i:s"),
					'expires_in'=>date("Y-m-d H:i:s",time()+$token['expires_in']),
					'openid'=>$token['openid'],
					'status'=>1,
				));
			}else{
				$oauth->save($oauth->create(array(
					'id'=>$id['id'],
					'update_time'=>date("Y-m-d H:i:s"),
					'expires_in'=>date("Y-m-d H:i:s",time()+$token['expires_in']),
				)));
			}
			if($type == 'sina')
				$param['param'] = array('uid'=>$sns->openid());
			 else
			 	$param['param'] = array();
			$user_info = \Think\Hook::listen('thinksdk', $param);

			echo("<h1>恭喜！使用 {$type} 用户登录成功</h1><br>");
			echo("授权信息为：<br>");
			dump($token);
			echo("当前登录用户信息为：<br>");
			dump($param);

			//TODO 自己处理登录或注册的事
			$user = array(
                'admin_id' => $user['id'],
                'admin_name' => $user['name'],
                'login_time' => NOW_TIME, //上次登录时间
            );
            //设置登录SESSION
            session(C('USER_AUTH_KEY'), $user);
            session(C('USER_AUTH_SIGN_KEY'), user_auth_sign($user));
            $this->success('登录成功', U('Admin/System/index'));
		}
	}

	//取消授权
	public function cancel(){
		//TODO自行实现，有的接口可能没这功能
	}

}
